package cn.idongjia.task.common.task;

import com.lts.core.commons.utils.StringUtils;
import com.lts.core.domain.Job;
import com.lts.core.domain.JobResult;
import org.apache.commons.cli.MissingArgumentException;

/**
 * Created by renxianlong on 16/4/7.
 */
public class JobToTask {
    public static final String EXCUTE_TYPE = "excute_type";

    public static final String TASK_TYPE = "task_type";

    public static final String FAULT_TYPE = "fault_type";

    public static final String CREATE_TIME = "create_time";

    public static final String SHELL_SCRIPT = "shell";

    public static Job convert(Task task){
        Job job = new Job();
        job.setExtParams(task.getExtParams());
        job.setParam(EXCUTE_TYPE,task.getExcuteType().name());
        job.setCronExpression(task.getCronExpression());
        job.setTriggerTime(task.getTriggerTime());
        job.setPriority(task.getPriority().getValue());
        job.setTaskTrackerNodeGroup(task.getExuterName());
        job.setMaxRetryTimes(task.getRetryTm());
        job.setTaskId(task.getTaskId());
        job.setParam(TASK_TYPE,task.getTaskType());
        job.setNeedFeedback(task.isNeedFeedBack());
        job.setParam(FAULT_TYPE,task.getFaultType().name());
        job.setParam(CREATE_TIME,String.valueOf(task.getCreateTm()));
        if(null != task.getShell()){
            job.setParam(SHELL_SCRIPT,task.getShell());
        }
        return job;
    }

    public static Task convert(Job job){
        Task task = new Task();
        String excutype = job.getParam(EXCUTE_TYPE);
        task.setExcuteType(ExcuteType.valueOf(null == excutype? ExcuteType.JAVA.name() : excutype));
        task.setCronExpression(job.getCronExpression());
        task.setTriggerTime(job.getTriggerTime());
        task.setPriority(Priority.fromValue(job.getPriority()));
        task.setExuterName(job.getTaskTrackerNodeGroup());
        task.setRetryTm(job.getMaxRetryTimes());
        task.setTaskType(job.getParam(TASK_TYPE));
        task.setTaskId(job.getTaskId());
        task.setNeedFeedBack(job.isNeedFeedback());
        String faultType = job.getParam(FAULT_TYPE);
        task.setFaultType(FaultType.valueOf(null == faultType ? FaultType.LOST.name() : faultType));
        String createTm = job.getParam(CREATE_TIME);
        task.setCreateTm(null == createTm ? System.currentTimeMillis() : Long.parseLong(createTm));
        task.setShell(job.getParam(SHELL_SCRIPT));
        task.setExtParams(job.getExtParams());
        return task;
    }

    public static TaskResult convert(JobResult jobResult){
        TaskResult taskResult = new TaskResult();
        taskResult.setMsg(jobResult.getMsg());
        taskResult.setSuccess(jobResult.isSuccess());
        taskResult.setTime(jobResult.getTime());
        taskResult.setTask(convert(jobResult.getJob()));
        return taskResult;
    }
}
